package com.rongshu.view.mediaPlayer.adapter;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.utils.Constant;
import com.rongshu.utils.DateUtils;
import com.rongshu.utils.GlideUtils;
import com.rongshu.view.mediaPlayer.activity.AudiobookPlayerActivity;
import com.rongshu.view.mediaPlayer.bean.AudiobookListResponse;
import com.rongshu.view.mediaPlayer.manager.PlayerManager;
import com.rongshu.view.mediaPlayer.service.PlayerService;
import com.rongshu.widget.ArticleLabelView;
import com.rongshu.widget.BarChartView;
import com.utils.permissions.OnPermission;
import com.utils.permissions.XXPermissions;
import com.widget.toast.ToastUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * created by zhengweis on 2019/4/25.
 * description：
 */
public class AudiobookListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    protected Context context;
    protected List<AudiobookListResponse.ResponseBean> list;
    private View mFooterView;
    //正常布局、Footer
    public int TYPE_NORMAL = 1;
    public int TYPE_FOOTER = 2;

    public AudiobookListAdapter(Context context, List<AudiobookListResponse.ResponseBean> list) {
        this.list = list;
        this.context = context;
    }

    public void setFooterView(View footerView) {
        mFooterView = footerView;
        notifyItemInserted(getItemCount() - 1);//注意这里
    }

    /**
     * 重写了getItemViewType方法，根据位置返回不同的ViewType
     */
    @Override
    public int getItemViewType(int position) {
        if (mFooterView == null) {
            return TYPE_NORMAL;
        }
        if (position == getItemCount() - 1) {
            return TYPE_FOOTER;
        }
        return TYPE_NORMAL;
    }

    /**
     * 根据不同的ViewType返回不同的item数量
     */
    @Override
    public int getItemCount() {
        if (mFooterView == null) {
            return list == null ? 0 : list.size();
        } else {
            return list == null ? 1 : list.size() + 1;
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        if (mFooterView != null && viewType == TYPE_FOOTER) {
            return new FooterViewHolder(mFooterView);
        }
        View view = LayoutInflater.from(context).inflate(R.layout.adapter_media_list_item, viewGroup, false);
        return new MediaViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder vH, final int i) {
        if (getItemViewType(i) == TYPE_FOOTER) {
            return;
        } else {
            MediaViewHolder viewHolder = (MediaViewHolder) vH;
            viewHolder.mediaName.setText(list.get(i).getTitle());
            viewHolder.mediaSummary.setText(list.get(i).getIntro());
            GlideUtils.loadImageView(context, viewHolder.mediaCover, list.get(i).getTopImg(),
                    R.drawable.default_preview_icon, R.drawable.default_preview_icon);
            if (list.get(i).getPlayState() && PlayerManager.getPlayer().isPlaying()) {
                viewHolder.mediaPlay.setVisibility(View.VISIBLE);
                viewHolder.mediaPlay.start();
            } else {
                viewHolder.mediaPlay.setVisibility(View.INVISIBLE);
                viewHolder.mediaPlay.stop();
            }
            //对比当前item日期 与 上一个item日期是否相同。不相同展示 月份view
            String currentTime = list.get(i).getDailyDate();
            String beforeTime = "";
            Date beforeDate = null;
            if (i > 0) {
                beforeTime = list.get(i - 1).getDailyDate();
                beforeDate = DateUtils.parseDate(DateUtils.YYYY_MM_DD_HH_MM_SS, beforeTime);
            }
            Date currentDate = DateUtils.parseDate(DateUtils.YYYY_MM_DD_HH_MM_SS, currentTime);
            SimpleDateFormat fmt = new SimpleDateFormat("yyyyMM");
            if (i != 0 &&
                    (TextUtils.isEmpty(beforeTime) || !TextUtils.equals(fmt.format(currentDate), fmt.format(beforeDate)))) {
                viewHolder.headContent.setVisibility(View.VISIBLE);
                Calendar cal = Calendar.getInstance();
                cal.setTime(currentDate);
                viewHolder.monthTv.setText((cal.get(Calendar.MONTH) + 1) + "月");
            } else {
                viewHolder.headContent.setVisibility(View.GONE);
            }

            viewHolder.mediaTime.setText(list.get(i).getMin());
            viewHolder.articleCategory.setText(list.get(i).getCategories());
            viewHolder.articleLabel.bindDatas(list.get(i).getKeywordList());
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (XXPermissions.isHasPermission(context, Manifest.permission.SYSTEM_ALERT_WINDOW)) {
                        Intent intent = new Intent(context, AudiobookPlayerActivity.class);
                        intent.putExtra(Constant.INTENT_DATA, list.get(i).getId());
                        context.startActivity(intent);
                    } else {
                        XXPermissions.with((Activity) context).permission(Manifest.permission.SYSTEM_ALERT_WINDOW).request(new OnPermission() {
                            @Override
                            public void hasPermission(List<String> granted, boolean isAll) {
                                context.startService(new Intent(context, PlayerService.class));
                                Intent intent = new Intent(context, AudiobookPlayerActivity.class);
                                intent.putExtra(Constant.INTENT_DATA, list.get(i).getId());
                                context.startActivity(intent);
                            }

                            @Override
                            public void noPermission(List<String> denied, boolean quick) {
                                ToastUtils.show(context.getString(R.string.audio_book_play_permission));
                            }
                        });
                    }
                }
            });
        }
    }

    class MediaViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.media_cover_img)
        ImageView mediaCover;
        @BindView(R.id.media_play_img)
        BarChartView mediaPlay;
        @BindView(R.id.media_name)
        TextView mediaName;
        @BindView(R.id.media_summary)
        TextView mediaSummary;
        @BindView(R.id.media_time)
        TextView mediaTime;
        @BindView(R.id.article_category)
        TextView articleCategory;
        @BindView(R.id.article_label)
        ArticleLabelView articleLabel;
        @BindView(R.id.head_content)
        RelativeLayout headContent;
        @BindView(R.id.month_tv)
        TextView monthTv;

        public MediaViewHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    class FooterViewHolder extends RecyclerView.ViewHolder {

        public FooterViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }
}
